package org.jeecg.modules.extbpm.job;

import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.TaskService;
import org.apache.commons.lang.time.DateFormatUtils;
import org.jeecg.common.api.dto.message.TemplateMessageDTO;
import org.jeecg.common.constant.CommonSendStatus;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.DySmsEnum;
import org.jeecg.common.util.DySmsHelper;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.bpm.dto.ActRuTaskDTO;
import org.jeecg.modules.bpm.mapper.ActivitiMapper;
import org.jeecg.modules.extbpm.process.common.WorkFlowGlobals;
import org.jeecgframework.core.util.ApplicationContextUtil;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.*;

/**
 * @Author scott
 * @Date 2019/11/7 18:30
 * @Description: 
 */
@Slf4j
public class TimeOutTask implements Job {

    private static TaskService taskService;
    private static ISysBaseAPI sysBaseAPI;
    private static ActivitiMapper activitiMapper;
    static {
        taskService = ApplicationContextUtil.getContext().getBean(TaskService.class);
        sysBaseAPI = ApplicationContextUtil.getContext().getBean(ISysBaseAPI.class);
        activitiMapper = ApplicationContextUtil.getContext().getBean(ActivitiMapper.class);
    }

    @Override
    public void execute(JobExecutionContext arg0) throws JobExecutionException {
        try {
            log.info("----------【定时任务】--任务超时提醒开始--------------");
            List<ActRuTaskDTO> list = activitiMapper.getTimeoutTask();
            if (list != null && list.size() > 0) {
                taskDeal(list);
            }
            log.info("-----------【定时任务】--任务超时提醒结束---------------");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void taskDeal(List<ActRuTaskDTO> list) {
        try {
            for (ActRuTaskDTO actRuTaskDTO : list) {
                //超时时间
                int nodeTimeout = actRuTaskDTO.getNodeTimeout();
                //流程发起时间
                Date startTime = actRuTaskDTO.getCreateTime();
                if (checkTimeOut(startTime, nodeTimeout)) {
                    log.info("-------------任务超时提醒-----startTime=" + startTime.toString()+",nodeTimeout="+nodeTimeout);
                    String taskId = actRuTaskDTO.getId();
                    String bpmBizTitle = (String) taskService.getVariable(taskId, WorkFlowGlobals.BPM_BIZ_TITLE);
                    //提醒模板
//                    StringBuilder sb = new StringBuilder("");
//                    sb.append("您有待处理的超时任务，任务信息如下：").append("\n");
//                    sb.append("标题：").append(bpmBizTitle).append("\n");
//                    sb.append("任务节点：").append((String) map.get("NAME_")).append("\n");
//                    sb.append("流程实例ID：").append((String) map.get("PROC_INST_ID_")).append("\n");
//                    sb.append("任务处理人：").append((String) map.get("ASSIGNEE_")).append("\n");
//                    String ctreatetime = startTime == null ? "" : DateFormatUtils.format(startTime, "yyyy-MM-dd HH:mm:ss");
//                    sb.append("任务开始时间：").append(ctreatetime);
//                    log.info("-------------任务超时-----msg----------" + sb.toString());
                    Map<String, String> mp = new HashMap<>();
                    mp.put("title",bpmBizTitle);
                    mp.put("task",actRuTaskDTO.getName());
                    mp.put("user",actRuTaskDTO.getAssignee());
                    mp.put("time",DateUtils.formatDateTime());
                    //系统通知
                    TemplateMessageDTO msg = new TemplateMessageDTO("系统", actRuTaskDTO.getAssignee(),"任务超时提醒",mp,CommonSendStatus.TZMB_BPM_CHAOSHI_TIP);
                    sysBaseAPI.sendTemplateAnnouncement(msg);
                    //sysBaseAPI.sendSysAnnouncement("系统", (String) map.get("ASSIGNEE_"), "任务超时提醒", sb.toString());
                    //短信通知接口
                    //邮件通知接口
                    //TODO
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 比较时间大小
     * @param startTime
     * @param timeout
     * @return
     */
    private boolean checkTimeOut(Date startTime, Integer timeout) {
        boolean flag = false;
        try {
            if (timeout == null || startTime == null) {
                return flag;
            }
            Calendar calSrc = Calendar.getInstance();
            Calendar calDes = Calendar.getInstance();
            calDes.setTime(startTime);
            int diff = DateUtils.dateDiff('h', calSrc, calDes);
            if (diff >= timeout) {
                flag = true;
            }
        } catch (Exception e) {
        }
        return flag;
    }

}
